#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>

int getnum(char *str)
{
  char res[3];
  char key[] = "0123456789";
  char * pch;
  pch = strpbrk (str, key);
  strncpy(res, pch, 3);
  return atoi(res);
}

int main(int argc, char **argv)
{
	if(argc < 4)
	{
		printf("Usage: %s result matrix1 matrix2 processors\n", argv[0]);
		return -1;
	}
	
	FILE *a = fopen(argv[2], "r");
	if(a == NULL)
		return -2;
	
	int a_filas, a_columnas;
	fread(&a_filas, sizeof(int), 1, a);
	fread(&a_columnas, sizeof(int), 1, a);
	fclose(a);
	
	FILE *b = fopen(argv[3], "r");
	if(b == NULL)
		return -3;
	
	int b_filas, b_columnas;
	fread(&b_filas, sizeof(int), 1,b);
	fread(&b_columnas, sizeof(int), 1, b);
	fclose(b);
	
	if(a_columnas != b_filas)
		return -4;
		
	char tmpfn[10] = "reqXXXXXX";

	FILE *tmp = fopen(mktemp(tmpfn), "w+");
	int i, endsection, section = (a_filas/atoi(argv[4]))+1;
	char prcfn[256], lastline[2048];
	
	sprintf(lastline, "fvar=`taskset -c 0 ./join %s %d %d", argv[1], a_filas, b_columnas);
	
	for(i = 0; i < atoi(argv[4]); i++)
	{
		endsection = (i+1)*section;
		if(endsection > a_filas)
			endsection = a_columnas;
		sprintf(prcfn, " prc%03d%03d%03d.tmp", getnum(argv[2]), getnum(argv[3]), i);
		fprintf(tmp, "taskset -c %d ./mult %s %s%s %d %d &\n", i+1, argv[2], argv[3], prcfn, (i * section), endsection);
		strcat(lastline, prcfn);
	}
	
	fprintf(tmp, "%s` \n", lastline);
	fprintf(tmp, "exit $fvar\n");
	fclose(tmp);
	chmod(tmpfn, S_IRUSR | S_IWUSR | S_IXUSR);
	
	sprintf(prcfn, "./%s", tmpfn);
	return (system(prcfn) >> 8);
	
}